layui.use(['layer', 'form', 'admin', 'ax', 'laytpl'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laytpl = layui.laytpl;

    var oldLimitArr = [];

    var serviceId = null;
    var limitArr = [];

    let id = system.getUrlParam("id");

    //获取所有可筛选服务
    var ajax = new $ax(system.contextPath + "/api/registry.service.lists");
    ajax.setType("get");
    var result = ajax.start();
    if (result.status) {
        var data = result.data;
        var list = [];
        for (var i = 0; i < data.length; i++) {
            var param = {};
            param['name'] = data[i];
            if (serviceId === data[i]) {
                param['checked'] = true;
            }
            list.push(param);
        }
        var data0 = {
            list: list,
        };
        var part0Temp = document.getElementById('part0-template');
        laytpl(part0Temp.innerHTML).render(data0, function (html) {
            document.getElementById('part0').innerHTML = html;
            form.render();
        });

        initRoteList();
    }

    //服务选择
    form.on('select(serviceId)', function (data) {
        serviceId = data.value;
        initRoteList();
    });

    //维度类型筛选
    form.on('checkbox(limit)', function (data) {
        if (data.elem.checked) {
            $('#' + data.value).removeClass('layui-hide');
            limitArr.push(data.value);
        } else {
            $('#' + data.value).addClass('layui-hide');
            var index = limitArr.indexOf(data.value);
            limitArr.splice(index, 1);
        }
    });

    //初始化路由筛选列表
    function initRoteList() {
        //路由列表加载
        var ajax = new $ax(system.contextPath + "/api/route.lists");
        ajax.setType("get");
        ajax.set({serviceId: serviceId});
        var result = ajax.start();
        if (result.status) {
            var data = result.data;
            var data0 = {
                list: data,
            };
            var part0Temp = document.getElementById('part1-template');
            laytpl(part0Temp.innerHTML).render(data0, function (html) {
                document.getElementById('part1').innerHTML = html;
                form.render();
            });
        }
    }

    //限流策略切换
    form.on('radio(limitType)', function (data) {
        $('.limitType').addClass('layui-hide');
        $('#limitType' + data.value).removeClass('layui-hide');
    });

    var tipsLayer;
    window.showTips = function (t) {
        const title = '限流策略';
        const windowRemark = '窗口策略：每秒处理固定数量的请求，超出请求数量返回错误信息。'
        const tokenRemark = '令牌桶策略：每秒放置固定数量的令牌数，每个请求进来后先去拿令牌，拿到了令牌才能继续，拿不到则等候令牌重新生成了再拿。'
        const content = title + '<br>' + windowRemark + '<br><br>' + tokenRemark
        //小tips
        tipsLayer = layer.tips(content, t, {
            tips: [1, '#8f8f8f'],
            time: 400000000
        })
    }

    window.closeTips = function () {
        layer.close(tipsLayer);
    }


    //获取限流基本信息
    var ajaxLimit = new $ax(system.contextPath + "/api/config.limit.get");
    ajaxLimit.setType("get");
    ajaxLimit.set({id: id});
    var resultLimit = ajaxLimit.start();
    if (resultLimit.status) {
        serviceId = resultLimit.data.serviceId;

        var routeId = resultLimit.data.routeId;
        var appKey = resultLimit.data.appKey;
        var limitIp = resultLimit.data.limitIp;
        var limitType = resultLimit.data.limitType;
        if (null != routeId && routeId != '') {
            document.getElementById('routeIdCheckbox').checked = true;
            $('#routeId').removeClass('layui-hide');
            limitArr.push('routeId');
            oldLimitArr.push('routeId');
        }

        if (null != appKey && appKey != '') {
            document.getElementById('appKeyCheckbox').checked = true;
            $('#appKey').removeClass('layui-hide');
            limitArr.push('appKey');
            oldLimitArr.push('appKey');
        }

        if (null != limitIp && limitIp != '') {
            document.getElementById('limitIpCheckbox').checked = true;
            $('#limitIp').removeClass('layui-hide');
            limitArr.push('limitIp');
            oldLimitArr.push('limitIp');
        }
        document.getElementById('limitTypeRadio' + limitType).checked = true;
        $('.limitType').addClass('layui-hide');
        $('#limitType' + limitType).removeClass('layui-hide');
        form.val('formContainer', resultLimit.data);
        form.render();
    }

    // 表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        if (limitArr.length == 0) {
            system.error("至少选择一个限流维度");
            return false;
        }

        for (var i = 0; i < limitArr.length; i++) {
            var limit = limitArr[i];
            if (data.field[limit] === '') {
                system.error(limit + '不能为空');
                return false;
            }
        }

        for (var i = 0; i < limitArr.length; i++) {
            var limit = limitArr[i];
            var index = oldLimitArr.indexOf(limit);
            oldLimitArr.splice(index, 1)
        }

        for (var i = 0; i < oldLimitArr.length; i++) {
            var limit = oldLimitArr[i];
            data.field[limit] = '';
        }

        var ajax = new $ax(system.contextPath + "/api/config.limit.add", function (res) {
            if (res.status) {
                system.success("添加成功！");
                //传给上个页面，刷新table用
                admin.putTempData('formOk', true);
                //关掉对话框
                admin.closeThisDialog();
            } else {
                system.error("添加失败！" + res.msg);
            }
        }, function (res) {
            system.error("添加失败！" + res.msg);
        });
        ajax.set(data.field);
        ajax.start();
        return false;
    });
});